package com.wtwd.device.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.wtwd.device.constant.Constant;
import com.wtwd.device.service.AppUserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * @author zdl
 * @Description
 * @create 2021-06-08 16:29
 */
@Configuration
public class MyBatisPlusConfig {

    @Resource
    private AppUserService appUserService;

    private final String APP_USER_TABLE = "app_user";

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        HashMap<String, TableNameHandler> map = new HashMap<String, TableNameHandler>() {
            {
                put("third_party_user", (sql, tableName) -> {
                    System.out.println("************---*--" + sql);
                    System.out.println("************---*--" + tableName);
                    return Constant.THREAD_LOCAL_TABLE.get();
                });
                put(APP_USER_TABLE, (sql, tableName) -> {
                    System.out.println("************---*--" + sql);
                    System.out.println("************---*--" + tableName);
                    String appName = appUserService.getLocalApp().getUserTable();
                    return appName;
                });
            }
        };
        dynamicTableNameInnerInterceptor.setTableNameHandlerMap(map);
        interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}
